﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace ProjectDeal.Helpers
{
    public static class HtmlHelpers
    {
        public static string Truncate(this HtmlHelper help, string content, int length)
        {
            if (content == null) return "";
            content = content.Replace("&nbsp;", " ");
            int f = content.IndexOf('<'), l = content.IndexOf('>');
            while (f >= 0 && f < l)
            {
                content = content.Remove(f, l - f + 1);
                f = content.IndexOf('<');
                l = content.IndexOf('>');
            }

            if (content.Length < length)
                return content;
            else
                return content.Substring(0, length) + "...";
        }
        public static string Truncate(string content, int length)
        {
            if (content == null) return "";
            content = content.Replace("&nbsp;", " ");
            int f = content.IndexOf('<'), l = content.IndexOf('>');
            while (f >= 0 && f < l)
            {
                content = content.Remove(f, l - f + 1);
                f = content.IndexOf('<');
                l = content.IndexOf('>');
            }

            if (content.Length < length)
                return content;
            else
                return content.Substring(0, length) + "...";
        }
        public static string FomartTime(this HtmlHelper help, DateTime? time)
        {

            if (time == null) return "";
            else
            {
                DateTime result = time.Value;
                return result.ToString("hh:mm:ss dd/MM/yyyy");
            }

        }
        public static string FomartTime(DateTime? time)
        {
            if (time == null) return "";
            else
            {
                DateTime result = time.Value;
                return result.ToString("hh:mm dd/MM/yyyy");
            }

        }
    
        //public static string EventEndTime(this HtmlHelper help, wh_Event _event)
        //{
        //    string result = "";
        //    if (_event.HasTimeEnd == true)
        //    {
        //        if (_event.EndTime != null)
        //        {
        //            result = result + _event.EndTime.Value.ToString("HH:mm dd/MM/yyyy");
        //        }
        //    }
        //    else
        //    {
        //        if (_event.EndTime != null)
        //        {
        //            result = result + _event.EndTime.Value.ToString("dd/MM/yyyy");
        //        }

        //    }

        //    return result;
        //}

        // Error: wh_Friend_GetByUserAndFriend
        //0: dang la ban be
        //1: minh gui request cho no
        //2: no request minh
        //public static int GetFriendStatus(this HtmlHelper help, Guid friendId)
        //{
        //    var userId = (Guid)Membership.GetUser().ProviderUserKey;

        //    if (userId == friendId) return 0;

        //    using (WhatsHotEntities db = new WhatsHotEntities())
        //    {
        //        var friend = db.wh_Friend_GetById(userId, friendId).Count() > 0 ?
        //            db.wh_Friend_GetById(userId, friendId).Single() : null;

        //        if (friend == null)
        //            return -1;
        //        else
        //            return friend.Status;

        //    }
        //}

        //return host url
        public static string GetHostUrl(this HtmlHelper help, HttpContext context)
        {
            string host = context.Request.Url.Scheme + "://" + context.Request.Url.Authority;
            return host;
        }
        public static string GetHostUrl(HttpContextBase context)
        {
            try
            {
                return context.Request.Url.Scheme + "://" + context.Request.Url.Authority;
            }
            catch (Exception ex)
            {
                return context.Request.UrlReferrer.Scheme + "://" + context.Request.UrlReferrer.Authority;
            }
        }
        public static string CreateFriendlyUrl(string title)
        {
            if (String.IsNullOrEmpty(title)) return "";
            title = locDau(title);
            //remove sign
            title = StringHelpers.convertToUnSign(title);
            // replace spaces with single dash
            title = Regex.Replace(title, @"\s+", "-");
            // if we end up with multiple dashes, collapse to single dash            
            title = Regex.Replace(title, @"\-{2,}", "-");

            // make it all lower case
            title = title.ToLower();
            // remove entities
            title = Regex.Replace(title, @"&\w+;", "");
            // remove anything that is not letters, numbers, dash, or space
            title = Regex.Replace(title, @"[^a-z0-9\-\s]", "");
            // replace spaces
            title = title.Replace(' ', '-');
            // collapse dashes
            title = Regex.Replace(title, @"-{2,}", "-");
            // trim excessive dashes at the beginning
            title = title.TrimStart(new[] { '-' });
            // if it's too long, clip it
            if (title.Length > 80)
                title = title.Substring(0, 79);
            // remove trailing dashes
            title = title.TrimEnd(new[] { '-' });
            return title;
        }

        public static string Linkify(string content)
        {
            string output = content;
            Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);

            MatchCollection mactches = regx.Matches(output);

            foreach (Match match in mactches)
            {
                output = output.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
            }
            string replaceWith = "<br/>";
            output = output.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
            return output;


        }
        private static readonly string[] FilterVietnameseword = new string[]
        {

            "aAeEoOuUiIdDyY",

            "áàạảãâấầậẩẫăắằặẳẵ",

            "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",

            "éèẹẻẽêếềệểễ",

            "ÉÈẸẺẼÊẾỀỆỂỄ",

            "óòọỏõôốồộổỗơớờợởỡ",

            "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",

            "úùụủũưứừựửữ",

            "ÚÙỤỦŨƯỨỪỰỬỮ",

            "íìịỉĩ",

            "ÍÌỊỈĨ",

            "đ",

            "Đ",

            "ýỳỵỷỹ",

            "ÝỲỴỶỸ"

        };
        private static string locDau(string str)
        {

            for (int i = 1; i < FilterVietnameseword.Length; i++)
            {

                for (int j = 0; j < FilterVietnameseword[i].Length; j++)

                    str = str.Replace(FilterVietnameseword[i][j], FilterVietnameseword[0][i - 1]);

            }

            return str;

        }
        public static TimeSpan ConvertHoursToTotalDays(double hours)
        {
            TimeSpan result = TimeSpan.FromHours(hours);

            return result;
        }
    }
    public class StringHelpers
    {
        public static string convertToUnSign(string s)
        {
            Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string temp = s.Normalize(NormalizationForm.FormD);
            return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }
    }
}